 <?php
/**
 * Joomla! 1.5 component PB-Roster
 *
 * @version $Id: pbroster.php 2010-09-10 10:03:33 svn $
 * @author ML@pixelbyte.dk
 * @package Joomla
 * @subpackage PB-Roster
 * @copyright (C) 2010- pixelbyte.dk
 * @license GNU/GPL
 *
 * A World of Warcraft Guild Roster
 *
 */

// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

function viewRoster($option) {

  $weupdated=0;

  if (checkUpdateDatabase()) {
    $weupdated = updateDatabase("");
  }

  $db =& JFactory::getDBO();
  $query = "SELECT * FROM #__guildroster_charinfo ORDER BY name";
  $db->setQuery($query);
  $rows = $db->loadObjectList();
  if ($db->getErrorNum()) {
    echo $db->getErrorMsg();
    //JError::raiseError(404, JText::_('viewRoster:Unable to load config'));
  }  
  HTML_Roster::showRoster($rows,$option);
}

function viewStats() {

  $db =& JFactory::getDBO();
  $query = "SELECT * FROM #__guildroster_charinfo";
  $db->setQuery($query);
  $rows = $db->loadObjectList();
  if ($db->getErrorNum()) {
    JError::raiseError(404, JText::_('viewStats:Unable to load config'));
  }
  HTML_Roster::showStats($rows,"");
}

function viewAccount() {

  if (isMemberLoggedIn()) {

    $account =& JFactory::getUser();
    $page = JRequest::getVar('page');
	$name = JRequest::getVar('ch');
    $claims = getClaimedCharacters($account->id);
  
    $db =& JFactory::getDBO();
    $query = "SELECT * FROM #__guildroster_charinfo WHERE jaccount ='$account->id'";
    $db->setQuery($query);
    $rows = $db->loadObjectList();
    if ($db->getErrorNum()) {
      JError::raiseError(404, JText::_('viewAccount:Unable to load config'));
    }
  
    if ($page == "unclaim") {
	  unClaimCharacter($name, $claims);
	  
	  $u =& JFactory::getURI();
      $u->setVar('view', 'account' );
	  $u->setVar('page', 'claims' );
	  echo "<meta http-equiv='refresh' content='3;URL=".$u->toString()."'>";
    }
	else if ($page == "setmain") {
	  setClaimedCharacterMain($account->id, $name);
	  
	  $u =& JFactory::getURI();
      $u->setVar('view', 'account' );
	  $u->setVar('page', 'claims' );
	  $u->delVar('ch');
	  echo "<meta http-equiv='refresh' content='3;URL=".$u->toString()."'>";
    }
	else if ($page == "edit_char") {
	  editClaimedCharacter($account->id, $name);
	  
	  $u =& JFactory::getURI();
      $u->setVar('view', 'account' );
	  $u->setVar('page', 'claims' );
	  $u->delVar('ch');
	  echo "<meta http-equiv='refresh' content='3;URL=".$u->toString()."'>";
    }
	else if ($page == "save_profile") {
	  editAccountProfile($account->id);
	  
	  $u =& JFactory::getURI();
      $u->setVar('view', 'account' );
	  $u->delVar('page');
	  echo "<meta http-equiv='refresh' content='3;URL=".$u->toString()."'>";
    }
	else if ($page == "save_options") {
	  editAccountOptions($account->id);
	  
	  $u =& JFactory::getURI();
      $u->setVar('view', 'account' );
	  $u->delVar('page');
	  echo "<meta http-equiv='refresh' content='3;URL=".$u->toString()."'>";
    }
	else if ($page == "options") {
	  HTML_MemberRoster::showMemberOptions($claims, "");
	}
	else if ($page == "claims") {
	  HTML_MemberRoster::showMemberAccountClaims($claims, "");
    }
	else
      HTML_MemberRoster::showMemberAccount($claims, "");
  }
  else {
    displayErrorMessage(JText::_( 'COM_PBROSTER_ERROR_INVALID_MEMBER_RIGHTS' ));
    $currentUrl = JURI::current();
	echo "<meta http-equiv='refresh' content='3;URL=".$currentUrl."'>";
  }
}

function viewAdmin() {

  if (!HTML_AdminRoster::getAdminRights()) {
    displayNoticeMessage(JText::_( 'COM_PBROSTER_ERROR_INVALID_ADMIN_RIGHTS' ));
    echo "<meta http-equiv='refresh' content='5;URL=".JRoute::_('index.php?option=com_pbroster&view=pbroster')."'>";
  }
  else {
	$page = JRequest::getVar('page');

	if ($page == "member") {
	  $db =& JFactory::getDBO();
      $query = "SELECT * FROM #__guildroster_charinfo";
      $db->setQuery($query);
      $rows = $db->loadObjectList();
      if ($db->getErrorNum()) {
        JError::raiseError(404, JText::_('viewAdmin:member:Unable to load config'));
      }
      HTML_AdminRoster::showMemberAdmin($rows,"");
	}
	else if ($page == "tabard") {
      if (getPlugin('tabard_designer')) {
        viewTabard();
	  }
	  else {
	    displayNoticeMessage(JText::_( 'COM_PBROSTER_PLUGIN_TABARD_DESIGNER_MISSING' ));
        echo "<meta http-equiv='refresh' content='3;URL=".JRoute::_('index.php?option=com_pbroster&view=pbroster')."'>";
	  }
	}
	else if ($page == "del_member") {
	  $member = $_POST['lookup_members'];
	  $member = urldecode($member); // Need to decode
	  
	  if ($member != " ")
	  {
	    // Extract the name only and remove everything after &
	    $member = substr($member, 0, strpos($member, "&"));
		displayNoticeMessage(JText::_( 'COM_PBROSTER_MESSAGE_NOTICE_DELETING' ).' '.$member);
	    // Remove any evil demons!
	    $name = mysql_real_escape_string($member);
	  
	    $db =& JFactory::getDBO();
	    $query = "DELETE FROM #__guildroster_charinfo WHERE name ='$name'";
	    $db->setQuery($query);
	    $db->query();
	  }
	  else
	    displayNoticeMessage(JText::_( 'COM_PBROSTER_MESSAGE_NOTICE_SELECT_MEMBER' ));
      echo "<meta http-equiv='refresh' content='5;URL=".JRoute::_('index.php?option=com_pbroster&view=admin&page=member')."'>";
	}
	else if ($page == "save_guildnote") {
	  updateGuildNote();
	  displayNoticeMessage(JText::_( 'COM_PBROSTER_ADMIN_FORM_MESSAGE_UPDATE_NOTE' ));
	
      echo "<meta http-equiv='refresh' content='2;URL=".JRoute::_('index.php?option=com_pbroster&view=admin&page=member')."'>";
	}
	else if ($page == "update_mlist") {
	
	  $memberlist = getMembers();
	  
	  foreach ( $memberlist as $member )
	    updateCharacterRoster($member,1,0);
	
      echo "<meta http-equiv='refresh' content='5;URL=".JRoute::_('index.php?option=com_pbroster&view=admin&page=member')."'>";
	}
	else if ($page == "add_member") {
	  $member = mysql_real_escape_string($_POST['addmember']);
	  
	  if ($member != "") {
	
	    $guild = getXMLData();
	    $armory_xml_file = 'character-sheet.xml';
		  
	    $char_data = new pb_xml_data();
	    $url = $guild->armory_server.$armory_xml_file.'?r='.$guild->realm.'&cn='.$member;
	    $xml_char_data = $char_data->get_xml($guild->lang,$url,1);

	    if (!$xml_char_data) {
		  displayNoticeMessage(JText::_( 'COM_PBROSTER_MESSAGE_NOTICE_ARMORY_DOWN' ));
	    }
	    else if ($xml_char_data->characterInfo->character['name'] == "") {
		  displayNoticeMessage($member.JText::_( 'COM_PBROSTER_MESSAGE_NOTICE_CH_NOT_FOUND' ));
	    }
	    else if ($xml_char_data->characterInfo['errCode'] == "noCharacter" || $xml_char_data->characterInfo['errCode'] == "badInput") {
		  displayNoticeMessage(JText::_( 'COM_PBROSTER_MESSAGE_NOTICE_ARMORY_ERROR' ).$xml_char_data->characterInfo['errCode']);
	    }
	    else {
		  $language = substr($guild->lang, 0, -3);
		  $bnet_realm = str_replace("+","-",$guild->realm);
		  if ($guild->region == "eu")
			$bnet = "http://eu.battle.net/wow/".$language."/character/".$bnet_realm."/";
		  else
			$bnet = "http://www.battle.net/wow/".$language."/character/".$bnet_realm."/";
			  
	      $mber->cache_date = date('Y-m-d H:i:s');
	      $mber->rank = 9; // Adding community rank
	      $mber->name = (string)$xml_char_data->characterInfo->character['name'];
          $mber->level = (int)$xml_char_data->characterInfo->character['level'];
          $mber->genderId = (int)$xml_char_data->characterInfo->character['genderId'];
          $mber->raceId = (int)$xml_char_data->characterInfo->character['raceId'];
          $mber->classId = (int)$xml_char_data->characterInfo->character['classId'];		  
		  $mber->charUrl = (string)'<a target="_blank" href="'.$bnet.$member.'/">';
		  
	      // Setting last_updated one hour back so it can be updated if requested
	      $mber->last_updated = date("Y-m-d H:i:s", strtotime("-1 hour"));
	      //Professions
	      $i=1;
	      foreach($xml_char_data->characterInfo->characterTab->professions->skill as $skill) {
		    if ($i==1) {
			  $prof1['id']    = (string)$skill['id'];
		      $prof1['name']  = (string)$skill['name'];
		      $prof1['value'] = (string)$skill['value'];
		      $prof1['max']   = (string)$skill['max'];
	        }
	        else if ($i==2) {
			  $prof2['id']    = (string)$skill['id'];
              $prof2['name']  = (string)$skill['name'];
              $prof2['value'] = (string)$skill['value'];
              $prof2['max']   = (string)$skill['max'];
            }
            $i++;
          }
	      $mber->prof1 = @serialize($prof1);
          $mber->prof2 = @serialize($prof2);
	      $mber->points = (int)$xml_char_data->characterInfo->character['points'];
		  
		  if (getPlugin('char_roster')) {  
	        $raw_data = new pb_raw_bnet_data();
		    $avatarId = $raw_data->get_avatar_id("http://".$guild->region.".battle.net/wow/en/character/".$bnet_realm."/".$mber->name."/tooltip");
		    $mber->avatar = (string)$avatarId;
	      }
			
	      $db =& JFactory::getDBO();
	      if ($db->insertObject('#__guildroster_charinfo', $mber)) {
		    displayNoticeMessage(JText::_( 'COM_PBROSTER_MESSAGE_NOTICE_ADDING_MEMBER' ).$member." this time!");
	      }
	      else // Lets assume the member already exist
		    displayNoticeMessage($member.JText::_( 'COM_PBROSTER_MESSAGE_NOTICE_ADDING_MEMBER_DUP_ONE' ).$member.JText::_( 'COM_PBROSTER_MESSAGE_NOTICE_ADDING_MEMBER_DUP_TWO' ), 1);
	    }
      }
	  else {
		displayNoticeMessage(JText::_( 'COM_PBROSTER_MESSAGE_NOTICE_ADDING_MEMBER_ERROR' ));
	  }
      echo "<meta http-equiv='refresh' content='5;URL=".JRoute::_('index.php?option=com_pbroster&view=admin&page=member')."'>";
    }
	else { // default
	  $db =& JFactory::getDBO();
      $query = "SELECT * FROM #__guildroster_main";
      $db->setQuery($query);
      $rows = $db->loadObjectList();
      if ($db->getErrorNum()) {
        JError::raiseError(404, JText::_('viewAdmin:guild:Unable to load guild config'));
      }
	  HTML_AdminRoster::showMemberAdmin($rows,"");
	}
  }
}

function getJoomlaUsers() {

  $db =& JFactory::getDBO();
  $query = "SELECT username FROM #__users";
  $db->setQuery($query);
  $rows = $db->loadObjectList();
  if ($db->getErrorNum()) {
    JError::raiseError(404, JText::_('getJoomlaUsers:Unable to get joom users'));
  }
  $users = array();
  if (count($rows)) {
    foreach ( $rows as $row )
	  $users[] = $row->username;
  }
  return $users;
}

function updateGuildNote() {
	  
  $db =& JFactory::getDBO();

  $note->id = 1;
  $note->guild_info = JRequest::getVar('guildnote');
  
  $db->updateObject('#__guildroster_main',$note,'id');
}

// Uncomment below to add more ranks
function return_rank($rankid) {

  /*if ($rankid >= 10) {
    switch ($rankid) {
        case  10: $rank = "name of rank";      break;
        case  11: $rank = "name of rank";      break;
		// add more if needed.
    }
    return $rank;
  }
  else {*/

    $db =& JFactory::getDBO();
    $query = "SELECT rank0, rank1, rank2, rank3, rank4, rank5, rank6, rank7, rank8, rank9 FROM #__guildroster_main";
    $db->setQuery($query);
    $rows = $db->loadRow();
    if ($db->getErrorNum()) {
      JError::raiseError(404, JText::_('return_rank:Unable to get info'));
    }
    return $rows[$rankid];
	
  //}
}

function return_class_id($name) {

  $db =& JFactory::getDBO();
  $query = "SELECT classId FROM #__guildroster_charinfo WHERE name='".$name."'";
  $db->setQuery($query);
  $rows = $db->loadObjectList();
  $id = "";
  if (count($rows)) {
    foreach ( $rows as $row )
	  $id = $row->classId;
  }
  return $id;
}

function getMembers() {

  $db =& JFactory::getDBO();
  $query = "SELECT name FROM #__guildroster_charinfo";
  $db->setQuery($query);
  $rows = $db->loadObjectList();
  if ($db->getErrorNum()) {
    JError::raiseError(404, JText::_('getMembers:Unable to get members'));
  }
  $users = array();
  if (count($rows)) {
    foreach ( $rows as $row )
	  $users[] = $row->name;
  }
  return $users;
}

function getNumMembers() {

  $db =& JFactory::getDBO();
  $query = "SELECT name FROM #__guildroster_charinfo";
  $db->setQuery($query);
  $db->query();
  
  $num_rows = $db->getNumRows();

  return $num_rows; 
}

function calculate_ilevel($name) {
  $db =& JFactory::getDBO();
  $query = "SELECT item_1, item_2, item_3, item_4, item_5, item_6, item_7, item_8, item_9, item_10, item_11, item_12, item_13, item_14, item_15, item_16, item_17, item_18, item_19 FROM #__guildroster_charinfo WHERE name ='$name'";
  $db->setQuery($query);
  $rows = $db->loadObjectList();
  
  $ilevel = 0;

  if (count($rows)) {
    foreach ( $rows as $row ) {
      $item = "";
	  $i = 1;
	  $ilev = 0;
	  $ilev_num = 0;
				
	  while ($i <= 19) {
	    switch ($i) {
		  case  1: $item = unserialize($row->item_1);  break; //head
		  case  2: $item = unserialize($row->item_2);  break; //neck
		  case  3: $item = unserialize($row->item_3);  break; //shoulder
		  case  4: $item = unserialize($row->item_4);  break; //shirt
		  case  5: $item = unserialize($row->item_5);  break; //chest
		  case  6: $item = unserialize($row->item_6);  break; //waist
		  case  7: $item = unserialize($row->item_7);  break; //legs
		  case  8: $item = unserialize($row->item_8);  break; //feet
		  case  9: $item = unserialize($row->item_9);  break; //wrist
		  case 10: $item = unserialize($row->item_10); break; //hands
		  case 11: $item = unserialize($row->item_11); break; //ring1
		  case 12: $item = unserialize($row->item_12); break; //ring2
		  case 13: $item = unserialize($row->item_13); break; //trinket1
		  case 14: $item = unserialize($row->item_14); break; //trinket2
		  case 15: $item = unserialize($row->item_15); break; //cloak
		  case 16: $item = unserialize($row->item_16); break; //mainhand
		  case 17: $item = unserialize($row->item_17); break; //offhand
		  case 18: $item = unserialize($row->item_18); break; //ranged
		  case 19: $item = unserialize($row->item_19); break; //tabard
	    }
				  
	    $i++;

	    if ($item['level'] == "")
	      continue;
				
	    if ($item['level'] > 99) {
	      $ilev += (int)$item['level'];
	    $ilev_num++;
	    }
	  }
	  if ($ilev_num >= 1)
	    $ilevel = floor($ilev/$ilev_num);
    }
  }
  return $ilevel;
}

function getMemberInfo() {

  $db =& JFactory::getDBO();
  $query = "SELECT name, level, genderId, raceId, classId FROM #__guildroster_charinfo ORDER BY name";
  $db->setQuery($query);
  $rows = $db->loadObjectList();
  if ($db->getErrorNum()) {
    JError::raiseError(404, JText::_('getMemberInfo:Unable to get members'));
  }
  return $rows;
}

function getMemberInfoNotes() {

  $db =& JFactory::getDBO();
  $query = "SELECT name, level, genderId, raceId, classId, prof1, prof2, talent_spec1, talent_spec2 FROM #__guildroster_charinfo ORDER BY name";
  $db->setQuery($query);
  $rows = $db->loadObjectList();
  if ($db->getErrorNum()) {
    JError::raiseError(404, JText::_('getMemberInfo:Unable to get members'));
  }
  return $rows;
}

function getGuildInfo() {

  $db =& JFactory::getDBO();
  $query = "SELECT * FROM #__guildroster_main";
  $db->setQuery($query);
  $rows = $db->loadObjectList();
  /*if ($db->getErrorNum()) {
    JError::raiseError(404, JText::_('getGuildInfo:Unable to get info'));
  }*/
  return $rows;
}

function getGuildConfig() {

  $db =& JFactory::getDBO();
  $query = "SELECT * FROM #__guildroster_main";
  $db->setQuery($query);
  $rows = $db->loadObjectList();
  $config = new stdClass;

  foreach ( $rows as $row ) {
    $config->roster_width = $row->roster_width;
	$config->roster_padding_top = $row->roster_padding_top;
	$config->roster_padding_left = $row->roster_padding_left;
	
	$config->table_ilevel = $row->table_ilevel;
	$config->table_ach = $row->table_ach;
	$config->table_level = $row->table_level;
	$config->table_role = $row->table_role;
	$config->table_race = $row->table_race;
	$config->table_class = $row->table_class;
	$config->table_prof1 = $row->table_prof1;
	$config->table_prof2 = $row->table_prof2;
	$config->table_rank = $row->table_rank;
	
	$config->table_ilevel_check = $row->table_ilevel_check;
    $config->table_prof1_check = $row->table_prof1_check;
    $config->table_prof2_check = $row->table_prof2_check;
    $config->table_role_check = $row->table_role_check;
	
	$config->table_default = $row->table_default;
	$config->table_sort = $row->table_sort;
	$config->table_entries = $row->table_entries;
	$config->roster_banner = $row->roster_banner;
	$config->menu_roster = $row->menu_roster;
	$config->menu_stats = $row->menu_stats;
	$config->menu_cal = $row->menu_cal;
	$config->menu_notes = $row->menu_notes;
	
	$config->enable_pbtheme = $row->enable_pbtheme;
	$config->theme_banner = $row->theme_banner;
	//$config->calendar_adjust = $row->calendar_adjust;
  }
  return $config;
}

function enabledCleanDB() {

  $db =& JFactory::getDBO();
  $query = "SELECT auto_delete FROM #__guildroster_main";
  $db->setQuery($query);
  $rows = $db->loadObjectList();
  if ($db->getErrorNum()) {
    JError::raiseError(404, JText::_('enabledCleanDB:Unable to get info'));
  }
  $enabled = "";
  if (count($rows)) {
    foreach ( $rows as $row )
	  $enabled = $row->auto_delete;
  }
  
  if ($enabled == "yes")
    return true;
  else
    return false;
}

function cleanDatabase() {

  if (enabledCleanDB()) {

    $xmlData = getXMLData();
	$armory_url = $xmlData->armory_server.'guild-info.xml?r='.$xmlData->realm.'&gn='.$xmlData->name;

    $guild_data = new pb_xml_data();
    $xml_guild_data = $guild_data->get_xml($xmlData->lang,$armory_url,0);

    if (!$xml_guild_data) {
      // do nothing
    }
    else
    {
      // Connect to the DB
      $db =& JFactory::getDBO();
	  // Array of current member names
	  $xMembers = getMembers();
	  $nMembers = array();

      foreach($xml_guild_data->guildInfo->guild->members->character as $char) {
	    $nMembers[] = $char['name'];
	  }
	  
	  //$result = array_merge(array_diff($nMembers, $xMembers));
	  $result = array_minus_array($xMembers, $nMembers);
	  
	  foreach($result as $dMembers) {
	    $query = "DELETE FROM #__guildroster_charinfo WHERE name='".$dMembers."' AND rank < 9"; // We only remove non community members (rank 9)
		$db->setQuery($query);
		$db->query();
	  }
    }
  }
}

function checkUpdateDatabase() {

  $db =& JFactory::getDBO();
  $query = "SELECT * FROM #__guildroster_main";
  $db->setQuery($query);

  $dbUpdateHours = 6; // How many hours before updating the database

  $cache = $db->loadObject();
  if( $db->getErrorNum() || !isset($cache) || !isset($cache->cache_date)) {
    return true;
  }

  $diff = time() - strtotime($cache->cache_date);
  $diffHours = $diff / 60 / 60;
  
  //echo $diffHours.'<br />';
  //echo $dbUpdateHours.'<br />';

  if ($diffHours > $dbUpdateHours)
    return true;
  return false;
}

function updateDatabase($option) {

  $xmlData = getXMLData();
  $armory_server = $xmlData->armory_server;
  $guild_region = $xmlData->region;
  $armory_url = $armory_server.'guild-info.xml?r='.$xmlData->realm.'&n='.$xmlData->name;
  
  $bnet_realm = str_replace("+","-",$xmlData->realm);
  $language = substr($xmlData->lang, 0, -3);
    
  if ($xmlData->region == "eu")
    $bnet = "http://eu.battle.net/wow/".$language."/character/".$bnet_realm."/";
  else
    $bnet = "http://www.battle.net/wow/".$language."/character/".$bnet_realm."/";

  $guild_data = new pb_xml_data();
  $xml_guild_data = $guild_data->get_xml($xmlData->lang,$armory_url,0);

  if (!$xml_guild_data) {
    return 0;
  }
  else
  {
    // Connect to the DB
    $db =& JFactory::getDBO();
    $member = new stdClass;
	// Array of current member names
	$cMembers = getMembers();
	// Get member names from the xml
	$xMembers = array();

    foreach($xml_guild_data->guildInfo->guild->members->character as $char)
    {
	  $member->name = (string)$char['name'];
      $member->cache_date = date('Y-m-d H:i:s');
	  $member->rank = (int)$char['rank'];
	  $member->level = (int)$char['level'];
      $member->genderId = (int)$char['genderId'];
      $member->raceId = (int)$char['raceId'];
      $member->classId = (int)$char['classId'];
	  
      //$member->charUrl = (string)'<a target="_blank" href="'.$armory_server.'character-sheet.xml?'.$char['url'].'">';
	  $member->charUrl = (string)'<a target="_blank" href="'.$bnet.$char['name'].'/">';
	  
	  if (getPlugin('char_roster')) {
	  
		// We only set achPoints if char_roster is not available because the armory guild list is not accurate.
	    $enabled = enabledPluginCRoster();
	    if (!$enabled) {
	      $member->points = (int)$char['achPoints'];
		}
	  }
	  else
	    $member->points = (int)$char['achPoints'];
	  
	  if (!in_array($char['name'], $cMembers)) { // New char
		// Setting last_updated one hour back so it can be updated if requested
		$member->last_updated = date("Y-m-d H:i:s", strtotime("-1 hour"));
	    
	    $db->insertObject('#__guildroster_charinfo', $member);
	  }
	  else {
		$db->updateObject('#__guildroster_charinfo', $member, 'name');
	  }
	  $xMembers[] = $char['name'];
	  
      // Update phpbb forum avatars
	  if (getPlugin('phpbb_avatar')) {
	    $enabled = enabledPluginPHPBB();
	    if ($enabled) {
          $avatar = "avatars/".$char['genderId']."-".$char['raceId']."-".$char['classId'].".gif";
          updatePHPBBAvatar($member->name, $avatar/*, $member->jaccount, $char['genderId'], $char['raceId'], $char['classId']*/);
	    }
	  }
    }

    // save the cache to the DB.
    $memberCache = new stdClass();
    $memberCache->id = 1;
    $memberCache->members = (int)$xml_guild_data->guildInfo->guildHeader['count'];
    $memberCache->cache_date = date('Y-m-d H:i:s');
	$memberCache->battleGroup = (string)$xml_guild_data->guildInfo->guildHeader['battleGroup'];
	$memberCache->faction = (string)$xml_guild_data->guildInfo->guildHeader['faction'];
	//$memberCache->name = (string)$xml_guild_data->guildInfo->guildHeader['name'];
	//$memberCache->realm = (string)$xml_guild_data->guildInfo->guildHeader['realm'];
	$memberCache->region = (string)$guild_region;
	
	// Get needed data from battle.net
	$raw_data = new pb_raw_bnet_data();
    $raw = $raw_data->get_guild_data("http://".$guild_region.".battle.net/wow/en/guild/".strtolower($bnet_realm)."/".str_replace("+","%20",(strtolower($xmlData->name)))."/");
	
	$memberCache->level = (int)$raw->level;
	$memberCache->achievement = (int)$raw->achievement;
	$memberCache->newsid = (int)$raw->newsid;
	
	// Guild Banner
	$memberCache->emblemBackground = (int)$xml_guild_data->guildInfo->guildHeader->emblem['emblemBackground'];
	$memberCache->emblemBorderColor = (int)$xml_guild_data->guildInfo->guildHeader->emblem['emblemBorderColor'];
	$memberCache->emblemBorderStyle = (int)$xml_guild_data->guildInfo->guildHeader->emblem['emblemBorderStyle'];
	$memberCache->emblemIconColor = (int)$xml_guild_data->guildInfo->guildHeader->emblem['emblemIconColor'];
	$memberCache->emblemIconStyle = (int)$xml_guild_data->guildInfo->guildHeader->emblem['emblemIconStyle'];
	
	if ($option == "update") {
	  $memberCache->rank0 = (string)mysql_real_escape_string($_POST['rank0']);
	  $memberCache->rank1 = (string)mysql_real_escape_string($_POST['rank1']);
	  $memberCache->rank2 = (string)mysql_real_escape_string($_POST['rank2']);
	  $memberCache->rank3 = (string)mysql_real_escape_string($_POST['rank3']);
	  $memberCache->rank4 = (string)mysql_real_escape_string($_POST['rank4']);
	  $memberCache->rank5 = (string)mysql_real_escape_string($_POST['rank5']);
	  $memberCache->rank6 = (string)mysql_real_escape_string($_POST['rank6']);
	  $memberCache->rank7 = (string)mysql_real_escape_string($_POST['rank7']);
	  $memberCache->rank8 = (string)mysql_real_escape_string($_POST['rank8']);
	  $memberCache->rank9 = (string)mysql_real_escape_string($_POST['rank9']);
	  
	  // Plugins
	  if (getPlugin('member_notes'))
	    $memberCache->plugin_notes = (string)mysql_real_escape_string($_POST['notes']);
	  if (getPlugin('char_roster'))
	    $memberCache->plugin_croster = (string)mysql_real_escape_string($_POST['croster']);
	  if (getPlugin('phpbb_avatar'))
	    $memberCache->plugin_phpbb = (string)mysql_real_escape_string($_POST['phpbb']);
	  if (getPlugin('quotes'))
	    $memberCache->plugin_quotes = (string)mysql_real_escape_string($_POST['quotes']);
		
	  $memberCache->auto_delete = (string)mysql_real_escape_string($_POST['auto_delete']);
	  $memberCache->update_hours = (int)$_POST['auto_update_hours'];
	  
	}

    $db = & JFactory :: getDBO();
    if (!$db->insertObject('#__guildroster_main',$memberCache,'id'))
	  $db->updateObject('#__guildroster_main',$memberCache,'id');
	
	cleanDatabase("");

	return 1;
  }
}

function getRealmList() {

$db =& JFactory::getDBO();
  $query = "SELECT title FROM #__guildroster_realmlist_eu";
  $db->setQuery($query);
  $rows = $db->loadResultArray();
  if ($db->getErrorNum()) {
    JError::raiseError(404, JText::_('getRealmList:Unable to get list'));
  }
  return $rows;
}

function getCountryList() {

  $db =& JFactory::getDBO();
  $query = "SELECT * FROM #__guildroster_countries";
  $db->setQuery($query);
  $rows = $db->loadObjectList();
  
  if ($db->getErrorNum()) {
    JError::raiseError(404, JText::_('getCountryList:Unable to get list'));
  }
  return $rows;
}

/*function test_table_name() {

  $db =& JFactory::getDBO();
  $query = "SELECT COUNT(jaccount) FROM #__guildroster_charinfo";
  $db->setQuery($query);
  $count = $db->loadResult();

  return $count;
}*/


function updateRealmList() {

  $data_eu = new pb_xml_data();
  $lang = "en";
  $url = 'http://www.wow-europe.com/realmstatus/index.xml';
  $xml_data_eu = $data_eu->get_xml($lang,$url,0);
  $db = & JFactory :: getDBO();
  $eu_list = new stdClass;
  
  foreach($xml_data_eu->channel->item as $eu) {
	$eu_list->title = mysql_real_escape_string($eu->title);
	
	if (!$db->insertObject('#__guildroster_realmlist_eu',$eu_list))
	  $db->updateObject('#__guildroster_realmlist_eu',$eu_list);
  }
  
  $data_us = new pb_xml_data();
  $lang = "en";
  $url = 'http://www.worldofwarcraft.com/realmstatus/index.xml';
  $xml_data_us = $data_us->get_xml($lang,$url,0);
  $us_list = new stdClass;
  
  foreach($xml_data_us->channel->item as $us) {
	// US use a different way to display realm names, so remove everything after " ("
	$tmp_title = substr($us->title, 0, strpos($us->title, " ("));
	
	$us_list->title = mysql_real_escape_string($tmp_title);
	
	if (!$db->insertObject('#__guildroster_realmlist_us',$us_list))
	  $db->updateObject('#__guildroster_realmlist_us',$us_list);
  }

}

?>